﻿using Gardener.Core.Api.Impl.AppManager.Entities;
using Gardener.Core.AppManager.Dtos;
using Gardener.Core.AppManager.Services;
using Microsoft.AspNetCore.Authorization;

namespace Gardener.Core.Api.Impl.AppManager.Services
{
    /// <summary>
    /// 应用版本服务
    /// </summary>
    [ApiDescriptionSettings(nameof(Constant.InfrastructureService), Module = "app-manager")]
    public class AppVersionService : ServiceBase<AppVersion, AppVersionDto, Int64>, IAppVersionService
    {
        private readonly IRepository<App> appRep;
        /// <summary>
        /// 应用版本服务
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="appRep"></param>
        public AppVersionService(IRepository<AppVersion> repository, IRepository<App> appRep) : base(repository)
        {
            this.appRep = appRep;
        }
        /// <summary>
        /// 查找新版本
        /// </summary>
        /// <remarks>
        /// 查找新版本
        /// </remarks>
        /// <param name="packageName"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<AppVersionDto?> FindNewVersion(string packageName, long version)
        {
            var entity = await _repository.AsQueryable(false).Where(x => !x.IsLocked && !x.IsDeleted && x.PackageName.Equals(packageName) && x.VersionNumber > version).OrderByDescending(x => x.VersionNumber).FirstOrDefaultAsync();
            if (entity != null)
            {
                App? app = await appRep.AsQueryable(false).FirstOrDefaultAsync(x => x.Id.Equals(entity.AppId) && !x.IsLocked && !x.IsDeleted);
                if (app == null)
                {
                    return null;
                }
                entity.App = app;
            }
            return entity?.Adapt<AppVersionDto>();
        }
    }
}
